package org.hako.recite.word.tool.writer;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.hako.recite.word.model.Word;
import org.hako.recite.word.parser.WordList;

/**
 * Writer word list to data file.
 * 
 * @since 0.4.9
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class DataFileWordListWriter extends AbstractWordListFileWriter {

	@Override
	public void write(WordList wordList, OutputStream outputStream)
			throws WordListWriteException {
		DataOutputStream stream = new DataOutputStream(outputStream);
		try {
			int columnCount = wordList.getColumnCount();
			int rowCount = wordList.getWordCount();
			stream.writeInt(columnCount);
			stream.writeInt(rowCount);
			String[] columnTitles = wordList.getColumnTitles();
			writeFields(stream, columnCount, columnTitles);
			for (Word word : wordList) {
				writeFields(stream, columnCount, word.getFields());
			}
			stream.flush();
		} catch (IOException e) {
			throw new WordListWriteException(e);
		}
	}

	/**
	 * Write fields.
	 * 
	 * @param stream
	 * @param columnCount
	 * @param fields
	 * @throws IOException
	 */
	private void writeFields(DataOutputStream stream, int columnCount,
			String[] fields) throws IOException {
		for (int column = 0; column < columnCount; column++) {
			stream.writeUTF(fields[column]);
		}
	}

}
